package com.chain.BrotherExchange.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chain.BrotherExchange.C;
import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.data.model.LegalTenderAppealOrderInfo;
import com.chain.BrotherExchange.data.model.LegalTenderOrderDetails;
import com.chain.BrotherExchange.event.LegalTenderOrderChangeEvent;
import com.chain.BrotherExchange.event.SubmitAppealSuccessEvent;
import com.chain.BrotherExchange.ui.core.AbsNetworkStateActivity;
import com.chain.BrotherExchange.ui.dialog.TransactionPasswordDialog;
import com.chain.BrotherExchange.utils.ActivityBarHelper;
import com.chain.BrotherExchange.utils.Androids;
import com.chain.BrotherExchange.viewmodel.OrderViewModel;
import com.chain.BrotherExchange.viewmodel.core.ViewModelProviders;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Date;

import butterknife.Bind;


/**
 * 出售法币订单详情
 */
public class LegalTenderSellOrderDetailsActivity extends AbsNetworkStateActivity {

    @Bind(R.id.state_text) TextView mStateTextView;
    @Bind(R.id.apply_button) Button mApplyButton;
    @Bind(R.id.count_down_text) TextView mCountDownTextView;
    @Bind(R.id.count_down_layout) LinearLayout mCountDownLayout;
    @Bind(R.id.user_avatar_image) ImageView mUserAvatarImage;
    @Bind(R.id.user_name_text) TextView mUserNameTextView;
    @Bind(R.id.unit_price_text) TextView mUnitPriceTextView;
    @Bind(R.id.number_text) TextView mNumberTextView;
    @Bind(R.id.order_time_text) TextView mOrderTimeTextView;
    @Bind(R.id.order_number_text) TextView mOrderNumberTextView;
    @Bind(R.id.price_text) TextView mPriceTextView;
    @Bind(R.id.payment_layout) LinearLayout mPaymentLayout;
    @Bind(R.id.negative_button) Button mNegativeButton;

    private int mPosition;
    private String mOrderId;
    private int mAppealState, mAppealId;
    private OrderViewModel mOrderViewModel;
    private LegalTenderOrderDetails.DataBean mLegalTenderOrderDetails;

    public static void launch(Context context, String id) {
        launch(context, id, 0, 0, -1);
    }

    public static void launch(Context context, String id, int appealState, int appealId, int position) {
        context.startActivity(new Intent(context, LegalTenderSellOrderDetailsActivity.class)
                .putExtra(C.EXTRA_ORDER_ID, id)
                .putExtra(C.EXTRA_POSITION, position)
                .putExtra(C.EXTRA_APPEAL_STATE, appealState)
                .putExtra(C.EXTRA_APPEAL_ID, appealId)
        );
    }

    @Override
    protected void setStatusBar() {
        ActivityBarHelper.setTransparentStatus(this);
    }

    @Override
    public int getTitleLayoutRes() {
        return R.layout.layout_screen_transparent_title_bar;
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_legal_tender_sell_order_details;
    }

    @Override
    protected void initActions() {
        ActivityBarHelper.init(this, R.string.title_order_details);
        mOrderId = getIntent().getStringExtra(C.EXTRA_ORDER_ID);
        mPosition = getIntent().getIntExtra(C.EXTRA_POSITION, -1);
        mAppealState = getIntent().getIntExtra(C.EXTRA_APPEAL_STATE, 0);
        mAppealId = getIntent().getIntExtra(C.EXTRA_APPEAL_ID, 0);
        mOrderViewModel = ViewModelProviders.of(this).get(OrderViewModel.class);
        initOrderDetailsInfo();
    }

    private void initOrderDetailsInfo() {
        mOrderViewModel.legalTenderOrderDetails(mOrderId).observe(this, resource ->
                Resource.load(this, resource, this, this::ontoOrderDetailsToView)
        );
    }

    private void ontoOrderDetailsToView(LegalTenderOrderDetails.DataBean result) {
        this.mLegalTenderOrderDetails = result;
        mUserAvatarImage.setImageResource(R.drawable.ic_placeholder_avatars);
        //ImageViews.load(result.get);
        mUserNameTextView.setText(result.getBuy_name()); // 用户昵称
        mUnitPriceTextView.setText(result.getPriceText() + "CNY"); // 单价
        mPriceTextView.setText(result.getTotalPrice()); // 价格
        mOrderTimeTextView.setText(new Date().toLocaleString()); // 下单时间
        mNumberTextView.setText(result.getNumText() + result.getToken_name()); // 数量
        mOrderNumberTextView.setText(result.getOrder_id()); // 订单号
        loadPayment(result); // 加载支付方式
        loadOrderState(result.getStatus()); // 加载订单状态
    }

    private void loadPayment(LegalTenderOrderDetails.DataBean result) {
        // 银行卡
        if (!TextUtils.isEmpty(result.getBank_name())) {
            ImageView imageView = new ImageView(this);
            imageView.setImageResource(R.drawable.ic_upcash_payment);
            imageView.setPadding(getResources().getDimensionPixelOffset(R.dimen.dp_8), 0, 0, 0);
            mPaymentLayout.addView(imageView, new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        }

        // 支付宝
        if (!TextUtils.isEmpty(result.getAlipay_name())) {
            ImageView imageView = new ImageView(this);
            imageView.setImageResource(R.drawable.ic_ali_payment);
            imageView.setPadding(getResources().getDimensionPixelOffset(R.dimen.dp_8), 0, 0, 0);
            mPaymentLayout.addView(imageView, new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        }

        // 微信
        if (!TextUtils.isEmpty(result.getWechat_name())) {
            ImageView imageView = new ImageView(this);
            imageView.setImageResource(R.drawable.ic_we_chat_payment);
            imageView.setPadding(getResources().getDimensionPixelOffset(R.dimen.dp_8), 0, 0, 0);
            mPaymentLayout.addView(imageView, new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        }

        // payPal
        if (!TextUtils.isEmpty(result.getPaypal_num())) {
            ImageView imageView = new ImageView(this);
            imageView.setImageResource(R.drawable.ic_pay_pal);
            mPaymentLayout.addView(imageView, new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        }
    }

    private void loadOrderState(int orderState) {
        switch (orderState) {
            case 1:
                waitingPayment();
                break;
            case 2:
                toBeReleased();
                break;
            case 3:
                completeTransaction();
                break;
            case 4:
                canceled();
                break;
        }
    }

    // 等待买家付款
    private void waitingPayment() {
        mStateTextView.setText(R.string.text_waiting_buyers_payment); // 订单状态
        mApplyButton.setVisibility(View.GONE);
        mNegativeButton.setVisibility(View.GONE);
    }

    // 待放行
    private void toBeReleased() {
        mStateTextView.setText(R.string.order_state_to_be_released); // 订单状态
        mApplyButton.setVisibility(View.VISIBLE);
        mNegativeButton.setVisibility(View.VISIBLE);

        mApplyButton.setText(R.string.text_confirm_receipt_release);
        mApplyButton.setOnClickListener(v -> {
            TransactionPasswordDialog.show(v.getContext(), dialog -> {
                int id = Integer.parseInt(mOrderId);
                mOrderViewModel.orderRelease(id, dialog.getPassword()).observe(this, resource -> {
                    if (resource.state == Resource.Status.LOADING) {
                        mApplyButton.setEnabled(false);
                    } else {
                        Androids.makeText(resource.message);
                        if (resource.state == Resource.Status.SUCCESS) {
                            dialog.dismiss();
                            loadOrderState(3);
                            EventBus.getDefault().post(new LegalTenderOrderChangeEvent(mPosition, 3));
                        }
                    }
                });
            });
        });

        if (mAppealState <= 0) {
            mNegativeButton.setText(R.string.appeal_immediately);
            mNegativeButton.setOnClickListener(v -> {
                String token_name = mLegalTenderOrderDetails.getToken_name();
                String order_id = mLegalTenderOrderDetails.getOrder_id();
                LegalTenderAppealActivity.launch(v.getContext(), new LegalTenderAppealOrderInfo(
                        token_name, order_id, 1, mLegalTenderOrderDetails.getToken_id()
                ), mPosition);
            });
        } else if (mAppealState == 1) {
//            mNegativeButton.setText("取消申诉");
//            mNegativeButton.setOnClickListener(v ->
//                    mOrderViewModel.cancelAppeal(mAppealId)
//                            .observe(this, resource -> {
//                                if (resource.state == Resource.Status.LOADING) {
//                                    mNegativeButton.setEnabled(false);
//                                } else {
//                                    Androids.makeText(resource.message);
//                                    if (resource.state == Resource.Status.SUCCESS) {
//                                        mAppealState = 4; // 取消申诉
//                                        toBeReleased();
//                                        EventBus.getDefault().post(new CancelAppealEvent());
//                                    }
//                                }
//                            })
//            );
        } else {
            mNegativeButton.setVisibility(View.GONE);
        }
    }

    // 交易完成
    private void completeTransaction() {
        mStateTextView.setText(R.string.complete); // 订单状态
        mApplyButton.setVisibility(View.GONE);
        mCountDownLayout.setVisibility(View.GONE);
        mNegativeButton.setVisibility(View.GONE);
    }

    // 订单取消
    private void canceled() {
        mStateTextView.setText(R.string.order_state_canceled);
        mApplyButton.setVisibility(View.GONE);
        mCountDownLayout.setVisibility(View.GONE);
        mNegativeButton.setVisibility(View.GONE);
    }

    @Subscribe
    public void submitAppealSuccessEvent(SubmitAppealSuccessEvent event) {
        mAppealState = 1;
        mAppealId = event.id;
        toBeReleased();
    }

    @Override
    public void onAnewRequest() {
        initOrderDetailsInfo();
    }
}
